#!/usr/local/bin/python
# -*- coding: utf-8 -*-

'''
用于处理【现金流量表】逻辑  CashFlowStatement
cash_flow_statement
'''
from datetime import datetime

from PyQt5 import QtWidgets
from PyQt5.QtWidgets import QWidget, QAbstractItemView, QTableWidgetItem
from dateutil.relativedelta import relativedelta

import init
import initCashFlowPage
import toolkit
from initLogger import logger
from ui.CashFlowStatementUI_relative_layout import Ui_CashFlowStatement
from CashFlow import CashFlow
from xToolkit.xstring import xstring


class CashFlowStatementWidget(QWidget, Ui_CashFlowStatement):
    def __init__(self):
        super(CashFlowStatementWidget, self).__init__()
        self.setupUi(self)

        self.currentDate = datetime.now()  #记录当前事件
        self.targetDate = self.currentDate  - relativedelta(days=init.GO_DAYS)#记录当前系统查看数据的时间
        self.initCashFlowStatement()

    def initCashFlowStatement(self):
        '''
        函数功能：初始化现金流表
        :return:
        '''
        logger.debug("call initCashFlowStatement")

        self.initCashFlowStatementUI()
        self.initCashFlowStatementPropertyTableUI()
        self.initCashFlowStatementOwnershipTableUI()

        self.initCashFlowStatementPropertyTableData()
        self.initCashFlowStatementOwnershipTableData()


    def initCashFlowStatementTitleUI(self):
        '''
        函数功能： 初始化现金流表的标题
        :return:
        '''
        cashFlowStatementTitleStr="%d年%d月——现金流表"%(self.targetDate.year, self.targetDate.month)
        self.title_label.setText(cashFlowStatementTitleStr)

    def initCashFlowStatementUI(self):
        '''
        函数功能：初始化现金流表的UI
        :return:
        '''
        logger.debug("call initCashFlowStatementUI")
        # 初始化标题
        self.initCashFlowStatementTitleUI()

        #初始化查询模块相关控件
        self.year_comboBox.addItems(init.YEAR_NAME_LIST)
        self.month_comboBox.addItems(init.MONTH_NAME_LIST)
        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

    def initCashFlowStatementPropertyTableUI(self):
        '''
        函数功能：初始化现金流表的资产部分的UI
        :return:
        '''
        logger.debug("call initCashFlowStatementPropertyTableUI")


        self.cash_flow_property_tableWidget.setRowCount(initCashFlowPage.CASH_FLOW_ROW_COUNT)  # 设置行数目
        self.cash_flow_property_tableWidget.setColumnCount(initCashFlowPage.CASH_FLOW_COLUMN_COUNT)  # 设置列数目
        self.cash_flow_property_tableWidget.setHorizontalHeaderLabels(initCashFlowPage.CASH_FLOW_COLUMN_CONTEXT)

        self.cash_flow_property_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        self.cash_flow_property_tableWidget.resizeColumnsToContents()  # 设置列宽自适应
        self.cash_flow_property_tableWidget.setShowGrid(True)  # 设置显示网络线
        self.cash_flow_property_tableWidget.setAlternatingRowColors(True)  # 设置表格颜色交错显示
        self.cash_flow_property_tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直标题
        self.cash_flow_property_tableWidget.horizontalHeader().setStretchLastSection(True)  # 设置最后一列自动填充容

        self.cash_flow_property_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置选中整行
        self.cash_flow_property_tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)  # 禁止编辑单元格


        self.cash_flow_property_tableWidget.setColumnWidth(0, 400)
        self.cash_flow_property_tableWidget.setColumnWidth(1, 150)
        self.cash_flow_property_tableWidget.setColumnWidth(2, 150)
        self.cash_flow_property_tableWidget.setColumnWidth(3, 150)

    def initCashFlowStatementOwnershipTableUI(self):
        '''
        函数功能：初始化现金流表的权属部分的UI
        :return:
        '''
        logger.debug("call initCashFlowStatementOwnershipTableUI")


        self.cash_flow_ownership_tableWidget.setRowCount(initCashFlowPage.CASH_FLOW_ROW_COUNT)  # 设置行数目
        self.cash_flow_ownership_tableWidget.setColumnCount(initCashFlowPage.CASH_FLOW_COLUMN_COUNT)  # 设置列数目
        self.cash_flow_ownership_tableWidget.setHorizontalHeaderLabels(initCashFlowPage.CASH_FLOW_COLUMN_CONTEXT)

        self.cash_flow_ownership_tableWidget.resizeRowsToContents()  # 设置行宽自适应
        self.cash_flow_ownership_tableWidget.resizeColumnsToContents()  # 设置列宽自适应
        self.cash_flow_ownership_tableWidget.setShowGrid(True)  # 设置显示网络线
        self.cash_flow_ownership_tableWidget.setAlternatingRowColors(True)  # 设置表格颜色交错显示
        self.cash_flow_ownership_tableWidget.verticalHeader().setVisible(False)  # 隐藏垂直标题
        self.cash_flow_ownership_tableWidget.horizontalHeader().setStretchLastSection(True)  # 设置最后一列自动填充容

        self.cash_flow_ownership_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)  # 设置选中整行
        self.cash_flow_ownership_tableWidget.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)  # 禁止编辑单元格

        self.cash_flow_ownership_tableWidget.setColumnWidth(0, 400)
        self.cash_flow_ownership_tableWidget.setColumnWidth(1, 150)
        self.cash_flow_ownership_tableWidget.setColumnWidth(2, 150)
        self.cash_flow_ownership_tableWidget.setColumnWidth(3, 150)

    def initCashFlowStatementPropertyTableData(self):
        '''
        函数功能：初始化现金流表资产部分的数据
        :return:
        '''
        logger.debug("call initCashFlowStatementPropertyTableData")
        cashFlow= CashFlow(year=self.targetDate.year, month=self.targetDate.month)
        cashFlowResult = cashFlow.getCashFlowDataMonthly(init.TYPE_PROPERTY)

        cashFlowLen =  len(cashFlowResult) + 1
        self.cash_flow_property_tableWidget.setRowCount(cashFlowLen)

        for i in range(len(cashFlowResult)):
            dataRow = cashFlowResult[i]
            subjectPathName= "%s\t" % (dataRow.path)
            subjectTotalPathWidgetItem = QTableWidgetItem(subjectPathName)
            self.cash_flow_property_tableWidget.setItem(i, 0, subjectTotalPathWidgetItem)


            inFlowValueStr = xstring.dispose(toolkit.processValueSignificant(dataRow.inflow_value)).humanized_amount(complex=True)
            inFlowTotalValueWidgetItem = QTableWidgetItem(inFlowValueStr)
            self.cash_flow_property_tableWidget.setItem(i, 1, inFlowTotalValueWidgetItem)

            outFlowTotalValueStr = xstring.dispose(toolkit.processValueSignificant(dataRow.outflow_value)).humanized_amount(complex=True)
            outFlowTotalValueWidgetItem = QTableWidgetItem(outFlowTotalValueStr)
            self.cash_flow_property_tableWidget.setItem(i, 2, outFlowTotalValueWidgetItem)

            differenceTotalValueStr = xstring.dispose(toolkit.processValueSignificant(dataRow.difference_value)).humanized_amount(complex=True)
            differenceTotalValueWidgetItem = QTableWidgetItem(differenceTotalValueStr)
            self.cash_flow_property_tableWidget.setItem(i, 3, differenceTotalValueWidgetItem)

        cashFlowTotalResult = cashFlow.getCashFlowTotalDataMonthly(init.TYPE_PROPERTY)
        if (len(cashFlowTotalResult)==0):
            return

        # 展示合计数据
        subjectTotalPathName = "%s\t" % (initCashFlowPage.PROPERTY_TOTAL_STR)
        subjectTotalPathWidgetItem = QTableWidgetItem(subjectTotalPathName)
        self.cash_flow_property_tableWidget.setItem(cashFlowLen-1, 0, subjectTotalPathWidgetItem)


        inFlowTotalValueStr = xstring.dispose(toolkit.processValueSignificant(cashFlowTotalResult[0].inflow_value)).humanized_amount(complex=True)
        inFlowTotalValueWidgetItem = QTableWidgetItem(inFlowTotalValueStr)
        self.cash_flow_property_tableWidget.setItem(cashFlowLen-1, 1, inFlowTotalValueWidgetItem)

        outFlowTotalValueStr = xstring.dispose(toolkit.processValueSignificant(cashFlowTotalResult[0].outflow_value)).humanized_amount(complex=True)
        outFlowTotalValueWidgetItem = QTableWidgetItem(outFlowTotalValueStr)
        self.cash_flow_property_tableWidget.setItem(cashFlowLen-1, 2, outFlowTotalValueWidgetItem)

        differenceTotalValueStr = xstring.dispose(toolkit.processValueSignificant(cashFlowTotalResult[0].difference_value)).humanized_amount(complex=True)
        differenceTotalValueWidgetItem = QTableWidgetItem(differenceTotalValueStr)
        self.cash_flow_property_tableWidget.setItem(cashFlowLen-1, 3, differenceTotalValueWidgetItem)


        return

    def initCashFlowStatementOwnershipTableData(self):
        '''
        函数功能：
        :return:初始化现金流表权属部分的数据
        '''
        logger.debug("call initCashFlowStatementOwnershipTableData")
        cashFlow = CashFlow(year=self.targetDate.year, month=self.targetDate.month)
        cashFlowResult = cashFlow.getCashFlowDataMonthly(init.TYPE_OWNERSHIP)

        cashFlowLen = len(cashFlowResult) + 1
        self.cash_flow_ownership_tableWidget.setRowCount(cashFlowLen)

        for i in range(len(cashFlowResult)):
            dataRow = cashFlowResult[i]
            subjectPathName = "%s\t" % (dataRow.path)
            subjectTotalPathWidgetItem = QTableWidgetItem(subjectPathName)
            self.cash_flow_ownership_tableWidget.setItem(i, 0, subjectTotalPathWidgetItem)

            inFlowValueStr = xstring.dispose(toolkit.processValueSignificant(dataRow.inflow_value)).humanized_amount(
                complex=True)
            inFlowTotalValueWidgetItem = QTableWidgetItem(inFlowValueStr)
            self.cash_flow_ownership_tableWidget.setItem(i, 1, inFlowTotalValueWidgetItem)

            outFlowTotalValueStr = xstring.dispose(
                toolkit.processValueSignificant(dataRow.outflow_value)).humanized_amount(complex=True)
            outFlowTotalValueWidgetItem = QTableWidgetItem(outFlowTotalValueStr)
            self.cash_flow_ownership_tableWidget.setItem(i, 2, outFlowTotalValueWidgetItem)

            differenceTotalValueStr = xstring.dispose(
                toolkit.processValueSignificant(dataRow.difference_value)).humanized_amount(complex=True)
            differenceTotalValueWidgetItem = QTableWidgetItem(differenceTotalValueStr)
            self.cash_flow_ownership_tableWidget.setItem(i, 3, differenceTotalValueWidgetItem)

        cashFlowTotalResult = cashFlow.getCashFlowTotalDataMonthly(init.TYPE_OWNERSHIP)
        if (len(cashFlowTotalResult) == 0):
            return

        # 展示合计数据
        subjectTotalPathName = "%s\t" % (initCashFlowPage.OWNERSHIP_TOTAL_STR)
        subjectTotalPathWidgetItem = QTableWidgetItem(subjectTotalPathName)
        self.cash_flow_ownership_tableWidget.setItem(cashFlowLen - 1, 0, subjectTotalPathWidgetItem)

        inFlowTotalValueStr = xstring.dispose(
            toolkit.processValueSignificant(cashFlowTotalResult[0].inflow_value)).humanized_amount(complex=True)
        inFlowTotalValueWidgetItem = QTableWidgetItem(inFlowTotalValueStr)
        self.cash_flow_ownership_tableWidget.setItem(cashFlowLen - 1, 1, inFlowTotalValueWidgetItem)

        outFlowTotalValueStr = xstring.dispose(
            toolkit.processValueSignificant(cashFlowTotalResult[0].outflow_value)).humanized_amount(complex=True)
        outFlowTotalValueWidgetItem = QTableWidgetItem(outFlowTotalValueStr)
        self.cash_flow_ownership_tableWidget.setItem(cashFlowLen - 1, 2, outFlowTotalValueWidgetItem)

        differenceTotalValueStr = xstring.dispose(
            toolkit.processValueSignificant(cashFlowTotalResult[0].difference_value)).humanized_amount(complex=True)
        differenceTotalValueWidgetItem = QTableWidgetItem(differenceTotalValueStr)
        self.cash_flow_ownership_tableWidget.setItem(cashFlowLen - 1, 3, differenceTotalValueWidgetItem)

        return

    def onGoLastMonth(self):
        """
        函数功能；展示上一个月的现金流表数据
        :return:
        """
        logger.debug("call onGoLastMonth")

        self.targetDate = toolkit.getLastMonth(self.targetDate, number=1)
        logger.debug("target year: %d   month: %d" % (self.targetDate.year, self.targetDate.month))
        self.clearCashFlowTableContext()

        self.initCashFlowStatementTitleUI()


        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

        self.initCashFlowStatementPropertyTableUI()
        self.initCashFlowStatementPropertyTableData()

        self.initCashFlowStatementOwnershipTableUI()
        self.initCashFlowStatementOwnershipTableData()

        return



    def onGoNextMonth(self):
        """
        函数功能；展示下一个月的现金流负债表数据
        :return:
        """
        logger.debug("call onGoNextMonth")

        self.targetDate = toolkit.getNextMonth(self.targetDate, number=1)
        logger.debug("target year: %d   month: %d" % (self.targetDate.year, self.targetDate.month))
        self.clearCashFlowTableContext()

        self.initCashFlowStatementTitleUI()


        self.year_comboBox.setCurrentText(str(self.targetDate.year))
        self.month_comboBox.setCurrentText(str(self.targetDate.month))

        self.initCashFlowStatementPropertyTableUI()
        self.initCashFlowStatementPropertyTableData()

        self.initCashFlowStatementOwnershipTableUI()
        self.initCashFlowStatementOwnershipTableData()

        return


    def onUpdateSheet(self):
        '''

        :return:
        '''
        logger.debug("call onUpdateSheet")

        cashFlow = CashFlow(self.targetDate.year, self.targetDate.month)
        cashFlow.genCashFlow()


        self.clearCashFlowTableContext()


        self.initCashFlowStatementTitleUI()

        self.initCashFlowStatementPropertyTableUI()
        self.initCashFlowStatementPropertyTableData()

        self.initCashFlowStatementOwnershipTableUI()
        self.initCashFlowStatementOwnershipTableData()



        return


    def onSearch(self):
        '''

        :return:
        '''
        logger.debug("call onSearch")
        year = int(self.year_comboBox.currentText())
        month = int(self.month_comboBox.currentText())

        self.targetDate = toolkit.setTargetDate(year, month)

        self.clearCashFlowTableContext()
        self.initCashFlowStatementTitleUI()

        self.initCashFlowStatementPropertyTableUI()
        self.initCashFlowStatementPropertyTableData()

        self.initCashFlowStatementOwnershipTableUI()
        self.initCashFlowStatementOwnershipTableData()




    def onUpdateAllYearSheet(self):
        '''
        函数功能：更新全年记账簿数据(暂缓实现)
        :return:
        '''
        logger.debug("call onUpdateAllYearSheet")


    def onPropertyTableDoubleClicked(self):
        '''
        函数功能：双击资产现金流表内容展示详细内容（暂未实现）
        :return:
        '''
        logger.debug("call onPropertyTableDoubleClicked")


    def onOwnershipTableDoubleClicked(self):
        '''
        函数功能：双击权属现金流表内容展示详细内容（暂未实现）
        :return:
        '''
        logger.debug("call onOwnershipTableDoubleClicked")




    def clearCashFlowTableContext(self):
        '''
        函数功能：清空资产负债表信息
        :return:
        '''

        self.cash_flow_property_tableWidget.clear()
        self.cash_flow_ownership_tableWidget.clear()
